package com.piece.admin.support;

import com.piece.admin.model.TbSysDept;
import com.piece.admin.model.TbSysPost;
import com.piece.admin.model.TbSysRole;
import com.piece.admin.model.TbSysUser;
import com.piece.admin.service.TbSysDeptService;
import com.piece.core.framework.constant.FrameWorkConstants;
import com.piece.core.framework.enums.OptionType;
import com.piece.core.framework.enums.StatusType;
import com.piece.core.framework.constant.PermissionConstants;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.util.object.BeanUtil;
import com.piece.core.framework.util.basic.SpringUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class UserInfoSupport {

    /**
     * 设置部门、角色组、岗位组相关信息
     */
    public static void setOtherInfo(TbSysUser user) {
        TbSysDeptService tbSysDeptService = SpringUtil.getBean(TbSysDeptService.class);

        // 外部用户不设置其它项
        if (OptionType.OPTION.getCode().equals(user.getUserType())) {
            return;
        }

        // 设置部门信息
        long deptId = user.getDeptId();
        TbSysDept dept = tbSysDeptService.findById(deptId);
        if (null != dept) {
            user.setDeptId(dept.getDeptId());
            user.setDeptName(dept.getDeptName());
        }

        // 设置角色组
        user.setRoleIds(selectUserRoleGroup(user.getUserId(), true));
        user.setRoleNames(selectUserRoleGroup(user.getUserId(), false));

        // 设置岗位组
        user.setPostIds(selectUserPostGroup(user.getUserId(), true));
        user.setPostNames(selectUserPostGroup(user.getUserId(), false));
    }

    /**
     * 查询用户所属角色组名称
     *
     * @param userId 用户ID
     * @param flag   true:返回id结果，false:返回name结果
     * @return 用户所有角色名称
     */
    public static String selectUserRoleGroup(Long userId, boolean flag) {
        List<TbSysRole> roles = getRole(userId);
        if (flag) {
            return roles.stream().map(role -> Convert.toStr(role.getRoleId())).collect(Collectors.joining(FrameWorkConstants.SPLIT_PARAM));
        } else {
            return roles.stream().map(role -> Convert.toStr(role.getRoleName())).collect(Collectors.joining(FrameWorkConstants.SPLIT_PARAM));
        }
    }

    /**
     * 查询用户所属岗位组名称
     *
     * @param userId 用户ID
     * @param flag   true:返回id结果，false:返回name结果
     * @return 用户所有职位名称
     */
    public static String selectUserPostGroup(Long userId, boolean flag) {
        List<TbSysPost> posts = getPost(userId);
        if (flag) {
            return posts.stream().map(post -> Convert.toStr(post.getPostId())).collect(Collectors.joining(FrameWorkConstants.SPLIT_PARAM));
        } else {
            return posts.stream().map(post -> Convert.toStr(post.getPostName())).collect(Collectors.joining(FrameWorkConstants.SPLIT_PARAM));
        }
    }

    public static List<String> getPermission(long userId) {
        JdbcTemplate jdbcTemplate = SpringUtil.getBean(JdbcTemplate.class);

        List<String> permissions = new ArrayList<>();
        String sql = "select distinct m.perms from `tb_sys_menu` m " +
                "left join `tb_sys_role_menu` rm on m.menu_id = rm.menu_id " +
                "left join `tb_sys_user_role` ur on rm.role_id = ur.role_id " +
                "where m.perms is not null and user_id = " + userId + " " +
                "union select distinct r.role_key from `tb_sys_role` r " +
                "left join `tb_sys_user_role` ur on r.role_id = ur.role_id " +
                "where r.role_key is not null and user_id = " + userId + " ";
        List<String> perms = jdbcTemplate.queryForList(sql, String.class);
        for (String perm : perms) {
            permissions.addAll(Arrays.asList(perm.trim().split(FrameWorkConstants.SPLIT_PARAM)));
        }

        return permissions;
    }

    public static List<TbSysRole> getRole(long userId) {
        JdbcTemplate jdbcTemplate = SpringUtil.getBean(JdbcTemplate.class);

        String sql = "select * from `tb_sys_role` where `role_id` in(select `role_id` from `tb_sys_user_role` " +
                "where `user_id` = " + userId + ") and `status` = '" + StatusType.NORMAL.getCode() + "'";
        return jdbcTemplate.query(sql, (rs, rowNum) -> {
            TbSysRole role = new TbSysRole();
            BeanUtil.resultSetToBean(rs, role);
            return role;
        });
    }

    public static List<TbSysPost> getPost(long userId) {
        JdbcTemplate jdbcTemplate = SpringUtil.getBean(JdbcTemplate.class);

        String sql = "select * from `tb_sys_post` where `post_id` in(select `post_id` from `tb_sys_user_post` where `user_id` = " + userId + ") " +
                "and `status` = '" + StatusType.NORMAL.getCode() + "'";
        return jdbcTemplate.query(sql, (rs, rowNum) -> {
            TbSysPost post = new TbSysPost();
            BeanUtil.resultSetToBean(rs, post);
            return post;
        });
    }

    public static boolean isAdminRole(long userId) {
        List<TbSysRole> roles = getRole(userId);
        List<String> role_keys = roles.stream().map(role -> Convert.toStr(role.getRoleKey())).collect(Collectors.toList());
        if (null != role_keys &&
                CollectionUtils.contains(role_keys.iterator(), PermissionConstants.ADMIN_PERMISSION)) {
            return true;
        }

        return false;
    }
}
